package com.bosssoft.cloud.wechat.core.api.impl;

import com.alibaba.fastjson.JSON;
import com.bosssoft.cloud.wechat.core.api.WxOAuth2Service;
import com.bosssoft.cloud.wechat.core.bean.oauth2.WxOAuth2AccessToken;
import com.bosssoft.cloud.wechat.core.infra.config.WxConfig;
import com.bosssoft.cloud.wechat.core.infra.enums.WxApiUrl;
import com.bosssoft.cloud.wechat.infrastructure.client.OkClient;
import com.bosssoft.cloud.wechat.infrastructure.enums.ErrEnum;
import com.bosssoft.cloud.wechat.infrastructure.exception.TPSException;
import com.bosssoft.cloud.wechat.infrastructure.util.Assert;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @author wcy create on 2021/6/23 15:04 下午
 */
@Service
public class WxOAuth2ServiceImpl implements WxOAuth2Service {

    @Resource
    private WxConfig wxConfig;
    @Resource
    private OkClient okClient;

    @Override
    public WxOAuth2AccessToken getAccessToken(String code) {
        return getAccessToken(wxConfig.getMpConfig().getMpAppId(), wxConfig.getMpConfig().getMpAppSecret(), code);
    }

    @Override
    public WxOAuth2AccessToken getAccessToken(String appid, String secret, String code) {
        String json = okClient.newClient()
                .runWx(WxApiUrl.OAuth2.OAUTH2_ACCESS_TOKEN_URL, appid, secret, code)
                .execute();
        WxOAuth2AccessToken token = JSON.parseObject(json, WxOAuth2AccessToken.class);
        if (token == null || token.getOpenId() == null)
            throw new TPSException(ErrEnum.C0612, json);
        return token;
    }
}
